declare const __dirname: string;

const path = require('path')
const fs = require('fs')
const resolve = (dir: string) => path.join(__dirname, '../../', dir)
const join = path.join
const utils = {path, fs, resolve, join}

interface IterateOption {
    path: string,
    handleFile?: (fileRelativePath: string) => void
    handleDirectory?: (directoryRelativePath: string) => void
    excludeFileRegexp?: RegExp | RegExp[],
    excludeDirectoryRegExp?: RegExp | RegExp[],
}

module.exports = {
    fs,
    resolve,
    /**
     * 获取文件状态
     * @author  韦胜健
     * @date    2020/6/19 9:19
     */
    getState(path: string) {
        try {
            return utils.fs.statSync(path)
        } catch (e) {
            return null
        }
    },
    /**
     * 扫描目录
     * @author  韦胜健
     * @date    2020/6/19 9:27
     * @param                   path                    要扫描得目录
     * @param                   handleFile              处理文件
     * @param                   handleDirectory         处理文件夹
     * @param                   excludeFileRegexp       排除处理的文件正则
     * @param                   excludeDirectoryRegExp  排除处理的文件夹正则
     */
    iterate({path, handleFile, handleDirectory, excludeFileRegexp, excludeDirectoryRegExp,}: IterateOption) {

        path = utils.path.normalize(path)
        const state = this.getState(path)

        if (!!state) {
            if (state.isFile()) {
                if (!!excludeFileRegexp && (Array.isArray(excludeFileRegexp) ? excludeFileRegexp.some(i => i.test(path)) : excludeFileRegexp.test(path))) {
                    return
                }
                !!handleFile && handleFile(path)
            } else {
                if (!!excludeDirectoryRegExp && (Array.isArray(excludeDirectoryRegExp) ? excludeDirectoryRegExp.some(i => i.test(path)) : excludeDirectoryRegExp.test(path))) {
                    return
                }
                !!handleDirectory && handleDirectory(path)
                const files = utils.fs.readdirSync(path)
                files.forEach((file: string) => {
                    this.iterate({
                        path: utils.join(path, file),
                        handleFile,
                        handleDirectory,
                        excludeFileRegexp,
                        excludeDirectoryRegExp,
                    })
                })
            }
        }
    },
}
